package com.dkts.oil.util;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.dkts.oil.config.JsonRedisTemplate;

@Component
public class RedisUtil implements ApplicationContextAware {
    static ApplicationContext applicationContext;
    static JsonRedisTemplate redisTemplate;

    @SuppressWarnings("null")
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        RedisUtil.applicationContext = applicationContext;
        RedisUtil.redisTemplate = (JsonRedisTemplate) applicationContext.getBean("jsonRedisTemplate");
    }

    public static void delete(String key) {
        redisTemplate.delete(key);
    }

    public static String get(String key, String defaultVal) {
        String val = (String) redisTemplate.opsForValue().get(key);
        return val == null ? defaultVal : val;
    }

    public static Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public static void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public static List<Object> listGetAll(String key) {
        Long size = redisTemplate.opsForList().size(key);
        if (size == null)
            return new ArrayList<Object>();
        return redisTemplate.opsForList().range(key, 0, size - 1);
    }

    public static void listDelItem(String key, Object value) {
        redisTemplate.opsForList().remove(key, 0, value);
    }

    public static void listRtPush(String key, Object value) {
        redisTemplate.opsForList().rightPush(key, value);
    }

    public static void listLtPush(String key, Object value) {
        redisTemplate.opsForList().leftPush(key, value);
    }

}